/**
 * Created by Sxd on 2014/9/28.
 */

/**
 * @class
 * @extends cc.Class
 * @property gameSocketState
 */
var NetManager = cc.Class.extend(/** @lends NetManager# */{

    /**
     * @type WebSocket
     */
    gameSocket: null,

    /**
     * @type xinyou.Packet
     */
    data: null,
    /**
     * @type xinyou.Packet
     */
    socketData: null,
    /**
     * @type {Object}
     */
    socketMsgHandler: null,

    init: function () {
        this.data = new xinyou.Packet();
        this.socketData = new xinyou.Packet(null, 65536);

        cc.defineGetterSetter(this, 'gameSocketState', this._gameSocketStateGetter);

        this.socketMsgHandler = {};
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGON, NetConstant.SUB_GS_LOGON_SUCCESS)] = [netStruct.LogonSuccess, xinyou.gameFrame.onSUB_GS_LOGON_SUCCESS];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGON, NetConstant.SUB_GS_LOGON_FAIL)] = [netStruct.LogonFail, xinyou.gameFrame.onSUB_GS_LOGON_FAIL];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGON, NetConstant.SUB_GS_LOGON_FINISH)] = [netStruct.LogonFinish, xinyou.gameFrame.onSUB_GS_LOGON_FINISH];

        //this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_INFO, NetConstant.SUB_GS_SERVER_INFO)] = [netStruct.ServerInfo, xinyou.gameFrame.onSUB_GS_SERVER_INFO];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_STATUS, NetConstant.SUB_GS_TABLE_INFO)] = [netStruct.GetTableListInfo, xinyou.gameFrame.onSUB_GS_TABLE_INFO];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_STATUS, NetConstant.SUB_GS_TABLE_STATUS)] = [netStruct.TableStatus, xinyou.gameFrame.onSUB_GS_TABLE_STATUS];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_SYSTEM, NetConstant.SUB_GS_SYSMESSAGE)] = [netStruct.SystemNotice, xinyou.gameFrame.onSUB_GS_SYSMESSAGE];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_USER, NetConstant.SUB_GS_USER_COME)] = [netStruct.GetUserItem, xinyou.gameFrame.onSUB_GS_USER_COME];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_USER, NetConstant.SUB_GS_USER_BANNED_STATUS)] = [netStruct.UserBannedStatus, xinyou.gameFrame.onSUB_GS_USER_BANNED_STATUS];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_USER, NetConstant.SUB_GS_USER_SIT_FAILED)] = [netStruct.UserSitFailed, xinyou.gameFrame.onSUB_GS_USER_SIT_FAILED];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_USER, NetConstant.SUB_GS_USER_STATUS)] = [netStruct.UserStatus, xinyou.gameFrame.onSUB_GS_USER_STATUS];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_USER, NetConstant.SUB_GS_USER_SCORE)] = [netStruct.UserScoreMSG, xinyou.gameFrame.onSUB_GS_USER_SCORE];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_SERVER_INFO, NetConstant.SUB_GS_ONLINE_CNT_INFO)] = [netStruct.OnlineCntInfoMSG, xinyou.gameFrame.onSUB_GS_ONLINE_CNT_INFO];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_FRAME, NetConstant.SUB_GS_MESSAGE)] = [netStruct.GS_Message, xinyou.gameFrame.onSUB_GS_MESSAGE];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_FRAME, NetConstant.SUB_GS_USER_CHAT_INGAME)] = [netStruct.UserChat, xinyou.gameFrame.onSUB_GS_USER_CHAT_INGAME];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_FRAME, NetConstant.SUB_GS_OPTION)] = [netStruct.GS_EX_Option, xinyou.gameFrame.onSUB_GS_OPTION];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_USER, NetConstant.SUB_GS_USER_SIT_REQ)] = [netStruct.User, xinyou.gameFrame.onSUB_GS_USER_ENTER];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETITEM)] = [netStruct.GoodStruct, xinyou.gameFrame.onSUB_GS_MARKETITEM];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETBUYCZ)] = [netStruct.GoodBuyCZ, xinyou.gameFrame.onSUB_GS_MARKETBUYCZ];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETBUYJB)] = [netStruct.GoodBuyJB, xinyou.gameFrame.onSUB_GS_MARKETBUYJB];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETBUYDJ)] = [netStruct.GoodBuyDJ, xinyou.gameFrame.onSUB_GS_MARKETBUYDJ];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETBUYSW)] = [netStruct.GoodBuySW, xinyou.gameFrame.onSUB_GS_MARKETBUYSW];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_GOODINFO)] = [netStruct.GoodInfo, xinyou.gameFrame.onSUB_GS_GOODINFO];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.SUB_GS_MYPROP)] = [netStruct.MyProp, xinyou.gameFrame.onSUB_GS_MYRPOP];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.SUB_GS_PAYINFO)] = [netStruct.PayInfo, xinyou.gameFrame.onSUB_GS_PAYINFO];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.SUB_GS_PAYRESULT)] = [netStruct.PayResult, xinyou.gameFrame.onSUB_GS_PAYRESULT];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_SIGN, NetConstant.SUB_GS_SIGN)] = [netStruct.MySign, xinyou.gameFrame.onSUB_GS_MYSIGN];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_SIGN, NetConstant.SUB_GS_SETSIGN)] = [netStruct.SetSign, xinyou.gameFrame.onSUB_GS_SETSIGN];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_SIGN, NetConstant.SUB_GS_GETSIGN)] = [netStruct.GetSign, xinyou.gameFrame.onSUB_GS_GETSIGN];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_RANK, NetConstant.SUB_GS_RANKLIST)] = [netStruct.GetRank, xinyou.gameFrame.onSUB_GS_RANK];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_MISSION, NetConstant.SUB_GS_MISSIONLIST)] = [netStruct.GetMission, xinyou.gameFrame.onSUB_GS_MISSION];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_MISSION, NetConstant.SUB_GS_MISSIONREWARD)] = [netStruct.GetMissionReward, xinyou.gameFrame.onSUB_GS_MISSIONREWARD];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_MISSIONREWARD)] = [netStruct.GetGameMissionReward, xinyou.gameFrame.onSUB_GS_GAMEMISSIONREWARD];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_MISSIONREWARD)] = [netStruct.InnerMission, xinyou.gameFrame.onSUB_GS_INNERMISSION];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_FRIENDLIST)] = [netStruct.GetFriend, xinyou.gameFrame.onSUB_GS_FRIEND];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_EDITFRIEND)] = [netStruct.EditFriend, xinyou.gameFrame.onSUB_GS_EDITFRIEND];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_FRIENDVERIFY)] = [netStruct.FriendVerify, xinyou.gameFrame.onSUB_GS_FRIENDVERIFY];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_FRIENDRESPONSE)] = [netStruct.FriendResponse, xinyou.gameFrame.onSUB_GS_FRIENDRESPONSE];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_SEARCHFRIEND)] = [netStruct.SearchFriend, xinyou.gameFrame.onSUB_GS_SEARCHFRIEND];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_TALK)] = [netStruct.GetTalk, xinyou.gameFrame.onSUB_GS_TALK];
        //历史聊天信息
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_HISTORYTALK)] = [netStruct.HistoryTalk, xinyou.gameFrame.onSUB_GS_HISTORYTALK];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_NOTICE, NetConstant.SUB_GS_HISTORYLABA)] = [netStruct.HistoryTalk, xinyou.gameFrame.onSUB_GS_HISTORYLABA];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_MAIL, NetConstant.SUB_GS_MAILLIST)] = [netStruct.GetMailList, xinyou.gameFrame.onSUB_GS_MAILLIST];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_MAIL, NetConstant.SUB_GS_MAILEDIT)] = [netStruct.MailEdit, xinyou.gameFrame.onSUB_GS_MAILEDIT];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_MAIL, NetConstant.SUB_GS_MAILINFO)] = [netStruct.GetMailInfo, xinyou.gameFrame.onSUB_GS_MAILINFO];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_MAIL, NetConstant.SUB_GS_SENDMAIL)] = [netStruct.SendMail, xinyou.gameFrame.onSUB_GS_SENDMAIL];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_REGISTER, NetConstant.SUB_GS_REGISTER)] = [netStruct.Register, xinyou.gameFrame.onSUB_GS_REGISTER];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGON, NetConstant.SUB_GS_LOGON_USERID)] = [netStruct.Login, xinyou.gameFrame.onSUB_GS_LOGIN];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_REGISTER, NetConstant.SUB_GS_ACCOUNT)] = [netStruct.Account, xinyou.gameFrame.onSUB_GS_ACCOUNT];
        //this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_USER, NetConstant.SUB_GS_CHANGE_INFO)] = [netStruct.ChangeInfo, xinyou.gameFrame.onSUB_GS_CHANGE_INFO];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.SUB_GS_USEPROP)] = [netStruct.UseProp, xinyou.gameFrame.onSUB_GS_USEPROP];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.SUB_GS_BEFOREUSEPROP)] = [netStruct.BeforeUseProp, xinyou.gameFrame.onSUB_GS_BEFOREUSEPROP];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_USELABA)] = [netStruct.UseLaba, xinyou.gameFrame.onSUB_GS_USELABA];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_POKECOUNT)] = [netStruct.PokeCount, xinyou.gameFrame.onSUB_GS_POKE_COUNT];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_USEPROPRESULT)] = [netStruct.UsePropResult, xinyou.gameFrame.onSUB_GS_USEPROPRESULT];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_EGG)] = [netStruct.GoldEgg, xinyou.gameFrame.onSUB_GS_EGG];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_GOLDEGG)] = [netStruct.GoldEgg, xinyou.gameFrame.onSUB_GS_GOLDEGG];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_CAN_EGG)] = [netStruct.CanGoldEgg, xinyou.gameFrame.onSUB_GS_CAN_EGG];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_EGGNAMELIST)] = [netStruct.EggNameList, xinyou.gameFrame.onSUB_GS_EGG_NAME_LIST];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_USER, NetConstant.SUB_GS_POCHAN)] = [netStruct.Pochan, xinyou.gameFrame.onSUB_GS_POCHAN];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_RUCHANG)] = [netStruct.Ruchang, xinyou.gameFrame.onSUB_GS_RUCHANG];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_LIAOTIAN)] = [netStruct.UserTalk, xinyou.gameFrame.onSUB_GS_USERTALK];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_INNER_USERINFO)] = [netStruct.InnerUserInfo, xinyou.gameFrame.onSUB_GS_INNER_USERINFO];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_KICK)] = [netStruct.GameKick, xinyou.gameFrame.onSUB_GS_GAME_KICK];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_CHEAT)] = [netStruct.GameCheat, xinyou.gameFrame.onSUB_GS_GAME_CHEAT];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_NOTICE, NetConstant.SUB_GS_NOTICE)] = [netStruct.GameNotice, xinyou.gameFrame.onSUB_GS_GAME_NOTICE];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_NOTICE, NetConstant.SUB_GS_GETRESTTIME)] = [netStruct.RestTime, xinyou.gameFrame.onSUB_GS_RESTTIME];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_NOTICE, NetConstant.SUB_GS_GONGGAO)] = [netStruct.Gonggao, xinyou.gameFrame.onSUB_GS_GONGGAO];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_NOTICE, NetConstant.SUB_GS_GETQQ)] = [netStruct.GetQQ, xinyou.gameFrame.onSUB_GS_GETQQ];
        this.socketMsgHandler[makeDWord(NetConstant.MAIN_NOTICE, NetConstant.SUB_GS_GETWX)] = [netStruct.GetWX, xinyou.gameFrame.onSUB_GS_GETWX];

        this.socketMsgHandler[makeDWord(NetConstant.JIHUO, NetConstant.MAIN_GS_LOGON)] = [netStruct.JiHuo, xinyou.gameFrame.onSUB_GS_JIHUO];

        this.socketMsgHandler[makeDWord(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_GETVIPDAYS)] = [netStruct.GetVIPDays, xinyou.gameFrame.onSUB_GS_GETVIPDAYS];
    },

    autoLogin: function () {
        //登陆
        var platForm = tyNamespace.Localstorage.getItem(tyNamespace.PLATFORM);
        var uniqueCode = tyNamespace.Localstorage.getItem(tyNamespace.UNIQUE_CODE);
        var userID = tyNamespace.Localstorage.getItem(tyNamespace.USER_ID_BYTE);
        var userName = tyNamespace.Localstorage.getItem(tyNamespace.USER_NAME);
        var password = tyNamespace.Localstorage.getItem(tyNamespace.USER_PASSWORD);

        xinyou.netManager.jihuo(platForm, uniqueCode);

        if (tyNamespace.checkStore(userID) && tyNamespace.checkStore(userName)) {
            var userIDByteArray = userID.split(",");

            xinyou.netManager.requestLogin(userIDByteArray, uniqueCode, userName, password);
        }

        if (tyNamespace.checkStore(userID) && !tyNamespace.checkStore(userName)) {
            var userIDByteArray = userID.split(",");

            xinyou.netManager.requestLogin(userIDByteArray, uniqueCode);
        }

        if (!tyNamespace.checkStore(userID) && tyNamespace.checkStore(userName)) {
            xinyou.netManager.requestLogin(userID, uniqueCode, userName, password);
        }
    },

    offLine: function () {
        var runningScene = cc.director.getRunningScene();
        var tyModelLayer = new tyNamespace.TyModelLayer();
        runningScene.addChild(tyModelLayer, 10);

        var offLineLayer = new tyNamespace.OffLineLayer();
        offLineLayer.attr({
            x: 0,
            y: cc.winSize.height
        });
        tyModelLayer.addChild(offLineLayer);

        offLineLayer.runAction(cc.moveBy(20 / 60, cc.p(0, -cc.winSize.height)).easing(cc.easeBackOut()));
    },

    initGameSocket: function (url, port, onopen, onerror, onclose) {
        var self = this;
        if (!cc.sys.isNative) {
            if (this.gameSocket && xinyou.objectExist(this.gameSocket) && (this.gameSocket.readyState == 1)) {
                this.closeGameSocket();
            }
        }

        var socketUrl = 'ws://' + url + ':' + port;
        cc.log("initGameSocket:" + socketUrl);

        this.gameSocket = new WebSocket(socketUrl);
        this.gameSocket.binaryType = 'arraybuffer';
        this.gameSocket.onopen = function () {
            xinyou.log('gameSocket连接成功');

            if (onopen)
                onopen();

            connectOpened = true;
            userInfo = null;

            //self.autoLogin();

            xinyou.gameFrame.dispatchEvent(NetEvent.GAME_SOCKET_CONNECTED, this)
        };

        this.gameSocket.onerror = function () {
            xinyou.log('gameSocket错误');
            if (self.gameSocketState == 1)
                self.closeGameSocket();

            if (onerror)
                onerror();

            connectOpened = false;

            self.offLine();

            xinyou.gameFrame.dispatchEvent(NetEvent.GAME_SOCKET_ERROR, this);
        };

        this.gameSocket.onclose = function () {
            xinyou.log('gameSocket关闭连接');
            if (self.gameSocketState == 1)
                self.closeGameSocket();

            if (onclose)
                onclose();

            connectOpened = false;

            self.offLine();

            xinyou.gameFrame.dispatchEvent(NetEvent.GAME_SOCKET_CLOSE, this);
        };

        this.gameSocket.onmessage = this.onGameSocketData.bind(this);
    },

    onGameSocketData: function (event) {
        if (!(event.data instanceof ArrayBuffer)) {
            return;
        }

        var by = new xinyou.Packet(event.data);

        this.socketData.appendBytes(by);

        //cc.log('this.socketData length:', this.socketData.length);

        while (1) {
            if (this.data.cmd == 0) {
                if (this.socketData.length < NetConstant.HEAD_SIZE) return;
                this.socketData.position = 0;
                this.data.readHead(this.socketData);
            }

            var msgBodyLength = this.data.msgLength - NetConstant.HEAD_SIZE;
            if (this.socketData.length < this.data.msgLength) return;

            if (msgBodyLength > 0) {
                this.data.writeBytes(this.socketData, NetConstant.HEAD_SIZE, msgBodyLength);
                this.socketData.position = this.socketData.position + msgBodyLength;
            }

            var cmd = parseDWord(this.data.cmd);
            var mainCMD = cmd[0];
            var subCMD = cmd[1];
            var byData = new xinyou.Packet();
            byData.writeBytes(this.data, NetConstant.HEAD_SIZE);
            byData.position = 0;
            byData.cmd = this.data.cmd;

            xinyou.log('收到消息: %d 0x%s 0x%s %d'+ Date.now()+ mainCMD.toString(16)+ subCMD.toString(16)+this.data.cmd);
            //xinyou.log("this.data.checkCode"+this.data.checkCode);

            if (this.socketMsgHandler[this.data.cmd]) {
                if (this.socketMsgHandler[this.data.cmd][0]) {
                    var msg = new this.socketMsgHandler[this.data.cmd][0](this.data.cmd);

                    //if (byData.bytesAvailable == 0 && this.data.checkCode == 1) {
                    //    cc.log("byData.bytesAvailable:" + byData.bytesAvailable);
                    //    this.data.clear();
                    //    this.socketData.clear();
                    //    return;
                    //}

                    msg.deserialize(byData);

                    this.socketMsgHandler[this.data.cmd][1].bind(xinyou.gameFrame)(msg);
                }
            }

            byData.position = 0;
            if (mainCMD == NetConstant.MAIN_GS_FRAME) {
                xinyou.gameFrame.onFrameMessage(subCMD, byData);
            }
            else if (mainCMD == NetConstant.MAIN_GS_GAME) {
                xinyou.gameFrame.onGameMessage(subCMD, byData);
            }
            else if (mainCMD == NetConstant.MAIN_GS_USER) {
                xinyou.gameFrame.onGameUserMessage(subCMD, byData);
            }
            else if (mainCMD == NetConstant.MAIN_GS_LOGON) {
                xinyou.gameFrame.onGameRoomLogin(subCMD, byData, this.data.checkCode);
            }

            this.data.clear();

            if (this.socketData.bytesAvailable > 0) {
                var tmp = new xinyou.Packet();
                tmp.writeBytes(this.socketData, this.socketData.position);
                this.socketData.clear();
                this.socketData.writeBytes(tmp);
                this.socketData.position = 0;
            }
            else {
                this.socketData.clear();
                return;
            }
        }
    },

    /**
     * 激活
     * @param platForm 平台
     * @param imei 唯一码
     */
    jihuo: function (platForm, imei) {
        var ba = new xinyou.ByteArray();

        ba.writeInt(platForm);
        ba.writeMyString(imei);

        this.sendGameSocketMsg(NetConstant.JIHUO, NetConstant.MAIN_GS_LOGON, ba);
    },

    /**
     * 登陆游戏
     * @param url 服务器地址
     * @param port 服务器端口
     * @param userName 用户名
     * @param password 密码
     * @param cb 错误回调 只有登陆失败才会回调
     */
    login: function (url, port, userName, password, cb) {
        var loginInfo;
        var retryCount = 0;
        if (singleGame) {
            var loginURL = cc.formatStr('http://web.hanyou.com/m/userinfo.do?account=%s&password=%s', userName, password);
            this.getJson(loginURL, function (err, result) {
                if (err) {
                    cb(err);
                }
                else if (result.code == 0) {
                    /**
                     * @type {vo.LoginInfo}
                     */
                    loginInfo = xinyou.gameFrame.meFromLogin;
                    loginInfo.userId = result.userId;
                    loginInfo.faceUrl = result.faceUrl;
                    loginInfo.medals = result.medals;
                    loginInfo.money = result.money;
                    loginInfo.nickName = result.nickName;
                    loginInfo.pwd = result.pwd;
                    loginInfo.score = result.score;
                    loginInfo.vip = result.vip;
                    connectGameSocket();
                } else {
                    cb(result.code, result.msg);
                }

            });
        }
        else {
            xinyou.gameFrame.meFromLogin = xy_userinfo;
            loginInfo = xy_userinfo;

            connectGameSocket();
        }

        function connectGameSocket() {
            if (retryCount >= 10) {
                return cb(408, '请检查网络连接');
            }
            retryCount++;
            xinyou.log("xygame", "connect url:" + url + " port:" + port);
            xinyou.netManager.initGameSocket(url, port, function () {
                xinyou.log("xygame", "login " + loginInfo.userId + " " + loginInfo.pwd);
                xinyou.netManager.requestUserLogin(loginInfo.userId, loginInfo.pwd);
            }, function () {
                xinyou.log("xygame", "connect error");
            }, connectGameSocket);
        }
    },

    /**
     * 获取历史聊天信息
     **/
    getHistoryTalk: function () {
    	cc.log("发送聊天信息请求");
        var ba = new xinyou.ByteArray();

        this.sendGameSocketMsg(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_HISTORYTALK, ba);
    },

    /**
     * 获取历史喇叭聊天信息
     **/
    getHistroyLaba: function () {
        var ba = new xinyou.ByteArray();

        this.sendGameSocketMsg(NetConstant.MAIN_NOTICE, NetConstant.SUB_GS_HISTORYLABA, ba);
    },

    /**
     * 注册
     * @param platform
     * @param headImageID
     * @param gender
     * @param unionCode
     * @param nickName
     * @param userName
     * @param password
     */
    requestRegister: function (platform, headImageID, gender, unionCode, nickName, userName, password, mail) {
        var ba = new xinyou.ByteArray();

        if (userName == undefined)
            ba.writeByte(1);
        else
            ba.writeByte(0);

        ba.writeInt(platform);
        ba.writeLong(headImageID);
        ba.writeMyString(gender);
        ba.writeMyString(unionCode);
        ba.writeMyString(nickName);
        var name = userName === undefined ? "" : userName;
        var pwd = password === undefined ? "" : password;
        var mail = mail === undefined ? "" : mail;
        ba.writeMyString(name);
        ba.writeMyString(pwd);
        ba.writeMyString(mail);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_REGISTER, NetConstant.SUB_GS_REGISTER, ba);
    },

    /**
     * 登陆到游戏服务器
     * @param userID
     * @param unionCode
     * @param userName
     * @param password
     */
    //requestLogin: function (userID, uniqueCode, userName, password) {
    //    var ba = new xinyou.ByteArray();
    //
    //    var userID = userID == null ? [] : userID;
    //    var name = userName === undefined ? "" : userName;
    //    var pwd = password === undefined ? "" : password;
    //    if (userID.length == 0)
    //        for (var a = 0; a < 8; a++) {
    //            ba.writeByte(0);
    //        }
    //    else {
    //        for (var a = 0; a < userID.length; a++) {
    //            ba.writeByte(userID[a]);
    //        }
    //    }
    //    ba.writeMyString(name);
    //    ba.writeMyString(pwd);
    //    ba.writeMyString(uniqueCode);
    //
    //    this.sendLoginMessage(NetConstant.SUB_GS_LOGON_USERID, ba);
    //},

    requestLogin: function (qq, nickName, headImgUrl) {
        var ba = new xinyou.ByteArray();

        ba.writeMyString(qq);
        ba.writeMyString(nickName);
        ba.writeMyString(headImgUrl);
        ba.writeMyString("");

        this.sendLoginMessage(NetConstant.SUB_GS_LOGON_USERID, ba);
    },

    /**
     * 绑定账号
     * @param userID
     * @param userName
     * @param password
     */
    bindingAccount: function (userName, password, mail) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(1);
        ba.writeMyString(userName);
        ba.writeMyString(password);
        ba.writeMyString(mail);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_REGISTER, NetConstant.SUB_GS_ACCOUNT, ba);
    },

    /**
     * 修改密码
     * @param userName
     * @param oldPassword
     * @param newPassword
     */
    changeAccount: function (userName, oldPassword, newPassword) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(0);
        ba.writeMyString(userName);
        ba.writeMyString(oldPassword);
        ba.writeMyString(newPassword);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_REGISTER, NetConstant.SUB_GS_ACCOUNT, ba);
    },

    /**
     * 修改个人信息
     * @param userHeadImageID
     * @param nickName
     * @param sex
     */
    changeUserInfo: function (userHeadImageID, nickName, sex) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(2);
        ba.writeLong(userHeadImageID);
        ba.writeMyString(nickName);
        ba.writeMyString(sex);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_REGISTER, NetConstant.SUB_GS_ACCOUNT, ba);
    },

    /**
     * 获取QQ群信息
     */
    getQQ: function () {
        var ba = new xinyou.ByteArray();

        this.sendGameSocketMsg(NetConstant.MAIN_NOTICE, NetConstant.SUB_GS_GETQQ, ba);
    },

    /**
     * 获取QQ群信息
     */
    getWXInfo: function () {
        var ba = new xinyou.ByteArray();

        this.sendGameSocketMsg(NetConstant.MAIN_NOTICE, NetConstant.SUB_GS_GETWX, ba);
    },

    /**
     * 游戏提示
     * type 游戏类型 1：列表 2：详情
     */
    getGonggao: function (type, id) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(type);
        if (id != undefined)
            ba.writeLong(id);

        this.sendGameSocketMsg(NetConstant.MAIN_NOTICE, NetConstant.SUB_GS_GONGGAO, ba);
    },

    /**
     * 游戏提示
     * gameType 游戏类型 0：大厅 1：麻将 2：斗地主
     */
    getGameNotice: function () {
        var ba = new xinyou.ByteArray();

        this.sendGameSocketMsg(NetConstant.MAIN_NOTICE, NetConstant.SUB_GS_NOTICE, ba);
    },

    /**
     * 游戏倒计时
     * gameType 游戏类型  1：金蛋 2：雀神，地主赛
     */
    getRestTime: function (type) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(type);

        this.sendGameSocketMsg(NetConstant.MAIN_NOTICE, NetConstant.SUB_GS_GETRESTTIME, ba);
    },

    /**
     * 入场
     * @param gameType 游戏类型 0：麻将 1：斗地主 2：德州
     */
    ruchang: function (gameType) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(gameType);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_RUCHANG, ba);
    },

    /**
     * 使用道具前
     * @param goodID
     * @param index
     */
    usePropBefore: function (goodID) {
        var ba = new xinyou.ByteArray();

        ba.writeLong(goodID);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.SUB_GS_BEFOREUSEPROP, ba);
    },

    /**
     * 使用道具
     * @param goodID
     * @param index
     */
    useProp: function (goodID, index, content) {
        var ba = new xinyou.ByteArray();

        ba.writeLong(goodID);
        ba.writeByte(index);
        if (content != undefined)
            ba.writeMyString(content);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.SUB_GS_USEPROP, ba);
    },

    /**
     * 使用记牌器   0:刚进入游戏 1:内部点击
     */
    pokeCount: function (type) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(type);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_POKECOUNT, ba);
    },

    /**
     * 查询砸金蛋获奖名字
     */
    getEggName: function () {
        var ba = new xinyou.ByteArray();

        this.sendGameSocketMsg(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_EGGNAMELIST, ba);
    },

    /**
     * 查询能否砸金蛋
     */
    canEgg: function () {
        var ba = new xinyou.ByteArray();

        this.sendGameSocketMsg(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_CAN_EGG, ba);
    },

    getInnerUserInfo: function (index) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(index);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_INNER_USERINFO, ba);
    },

    /**
     * 领取破产补助
     */
    getPochanGold: function () {
        var ba = new xinyou.ByteArray();

        this.sendGameSocketMsg(NetConstant.MAIN_GS_USER, NetConstant.SUB_GS_POCHAN, ba);
    },

    /**
     * 购买一元RMB礼包
     */
    buyRMB: function (goodID) {
        var ba = new xinyou.ByteArray();

        ba.writeLong(goodID);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETBUYCZ, ba);
    },

    /**
     * 游戏内部聊天表情
     */
    userTalk: function (talkID) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(talkID);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_LIAOTIAN, ba);
    },

//    /**
//     * 登陆到游戏服务器
//     * @param logName logName
//     */
//    requestLogNameLogin:function (userID) {
//    	var ba = new xinyou.ByteArray();
//    	ba.writeByte(0);
//    	ba.writeLong(userID);
//    	ba.writeMyString("唯一码13231");
//
//    	xinyou.log("xygame", "login uid:" + userID);
//    	this.sendLoginMessage(NetConstant.SUB_GS_LOGON_USERID, ba);
//    },

    /**
     * 登陆到 快速充值
     */
    inQuickCharge: function () {
        var ba = new xinyou.ByteArray();

        ba.writeByte(1);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETITEM, ba);
    },

    /**
     * 登陆到 游戏币兑换
     */
    inGoldExchange: function () {
        var ba = new xinyou.ByteArray();

        ba.writeByte(2);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETITEM, ba);
    },

    /**
     * 登陆到 道具兑换
     */
    inPropExchange: function () {
        var ba = new xinyou.ByteArray();

        ba.writeByte(3);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETITEM, ba);
    },

    /**
     * 登陆到 实物兑换
     */
    inPhysicalExchange: function () {
        var ba = new xinyou.ByteArray();

        ba.writeByte(4);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETITEM, ba);
    },

    /**
     * 商城物品购买  rmb充值
     * @param 商品id
     */
    buyGoodsCz: function () {
        var ba = new xinyou.ByteArray();
        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETBUYCZ, ba);
    },

    /**
     * 商城物品购买  金币购买
     * @param 商品id
     * @param 商品个数
     */
    buyGoodsJb: function (goodID, quantity) {
        var ba = new xinyou.ByteArray();

        ba.writeLong(goodID);
        ba.writeInt(quantity);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETBUYJB, ba);
    },

    /**
     * 商城物品购买  道具购买
     * @param 商品id
     * @param 数量
     */
    buyGoodsDj: function (goodID, quantity) {
        var ba = new xinyou.ByteArray();

        ba.writeLong(goodID);
        ba.writeInt(quantity);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETBUYDJ, ba);
    },

    /**
     * 商城物品购买  实物兑换
     * @param 商品id
     */
    buyGoodsSw: function (goodID) {
        var ba = new xinyou.ByteArray();

        ba.writeLong(goodID);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_MARKETBUYSW, ba);
    },

    /**
     * 商城详细信息
     * @param 商品id
     */
    getGoodInfo: function (goodID) {
        var ba = new xinyou.ByteArray();

        ba.writeLong(goodID);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.MAIN_GS_GOODINFO, ba);
    },

    /**
     * 我的道具
     */
    myPropInfo: function () {
        var ba = new xinyou.ByteArray();
        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.SUB_GS_MYPROP, ba);
    },

    /**
     * 获得支付信息
     */
    getPayInfo: function (goodID) {
        var ba = new xinyou.ByteArray();

        ba.writeLong(goodID);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGIN_MARKET, NetConstant.SUB_GS_PAYINFO, ba);
    },

    /**
     * 我的签到
     */
    getSign: function () {
        var ba = new xinyou.ByteArray();
        this.sendGameSocketMsg(NetConstant.MAIN_GS_SIGN, NetConstant.SUB_GS_SIGN, ba);
    },

    /**
     * 签到  1、补签  0
     */
    setSign: function (type) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(type);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_SIGN, NetConstant.SUB_GS_SETSIGN, ba);
    },

    /**
     * 兑换
     */
    duihuan: function (id) {
        var ba = new xinyou.ByteArray();

        ba.writeLong(id);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_SIGN, NetConstant.SUB_GS_GETSIGN, ba);
    },

    /**
     * 我的邮件
     */
    getMail: function (mailType) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(mailType);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_MAIL, NetConstant.SUB_GS_MAILLIST, ba);
    },

    /**
     * 编辑收件箱邮件 1：领取 2：全部领取 3：删除 4：全部删除
     */
    mailEdit: function (editType, mailID) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(editType);
        if (mailID != undefined)
            ba.writeLong(mailID);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_MAIL, NetConstant.SUB_GS_MAILEDIT, ba);
    },

    /**
     * 发送邮件
     */
    sendMail: function (nickName, title, content, goldCount) {
        var ba = new xinyou.ByteArray();

        ba.writeMyString(nickName);
        ba.writeMyString(title);
        ba.writeMyString(content);
        ba.writeByte(1);
        ba.writeInt(1);
        ba.writeInt(goldCount);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_MAIL, NetConstant.SUB_GS_SENDMAIL, ba);
    },

    /**
     * 我的邮件 单个邮件详细信息
     */
    getMailInfo: function (mailID) {
        var ba = new xinyou.ByteArray();

        ba.writeLong(mailID);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_MAIL, NetConstant.SUB_GS_MAILINFO, ba);
    },

    /**
     * 进入排行榜  1大厅排行榜，2雀神，3开心地主 4,5,6前十后十
     */
    getRank: function (type) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(type);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_RANK, NetConstant.SUB_GS_RANKLIST, ba);
    },

    /**
     * 我的任务
     * @param missionType byte 大厅任务显示 1 游戏中任务显示 2
     * @param roomType int 麻将 0  斗地主 1  德州扑克 2 所有 3
     * @param subRoomType int 初级场-大神场 1 - 6
     */
    myMission: function (missionType, roomType, subRoomType) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(missionType);
        ba.writeInt(roomType);
        if (subRoomType != undefined)
            ba.writeInt(subRoomType);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_MISSION, NetConstant.SUB_GS_MISSIONLIST, ba);
    },

    missionReward: function (missionID, roomType) {
        var ba = new xinyou.ByteArray();

        ba.writeLong(missionID);
        ba.writeInt(roomType);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_MISSION, NetConstant.SUB_GS_MISSIONREWARD, ba);
    },

    /**
     * 进入好友
     */
    getFriend: function () {
        var ba = new xinyou.ByteArray();
        this.sendGameSocketMsg(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_FRIENDLIST, ba);
    },

    /**
     * 编辑好友  editType 1：添加，0：删除
     */
    editFriend: function (editType, friendID) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(editType);
        ba.writeLong(friendID);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_EDITFRIEND, ba);
    },

    /**
     * 获取好友验证列表
     */
    getFriendMessage: function () {
        var ba = new xinyou.ByteArray();
        this.sendGameSocketMsg(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_FRIENDVERIFY, ba);
    },

    /**
     * 发送好友聊天
     * @param talkType  1 私聊  2 公聊
     * @param toID 别人的ID
     * @param contents 内容
     */
    sendTalkShort: function (talkType, toID, contents) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(talkType);
        if (toID != null)
            ba.writeLong(toID);
        ba.writeMyString(contents);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_TALK, ba);
    },

    feedback: function (type, number, content) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(type);
        if (type == 4)
            ba.writeByte(number);
        else {
            ba.writeMyString(number);
            ba.writeMyString(content);
        }

        this.sendGameSocketMsg(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_CHEAT, ba);
    },

    /**
     * 发送好友聊天
     * @param talkType  1 私聊  2 公聊
     * @param toID 别人的ID
     * @param contents 内容
     */
    sendTalk: function (talkType, toID, contents) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(talkType);
        if (toID != null && toID.length != 0) {
            for (var a = 0; a < toID.length; a++) {
                ba.writeByte(toID[a]);
            }
        }
        ba.writeMyString(contents);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_TALK, ba);
    },

    /**
     * 添加好友响应   responseType  1 确定，2 取消，3 全部添加，4 全部取消    userID  单加发送
     */
    addFriendResponse: function (responseType, userID) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(responseType);
        var userID = userID == undefined ? [] : userID;
        if (userID.length != 0) {
            for (var a = 0; a < userID.length; a++) {
                ba.writeByte(userID[a]);
            }
        }

        this.sendGameSocketMsg(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_FRIENDRESPONSE, ba);
    },

    /**
     * 搜索好友
     */
    searchFriend: function (id) {
        var ba = new xinyou.ByteArray();

        ba.writeMyString(id);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_FRIEND, NetConstant.SUB_GS_SEARCHFRIEND, ba);
    },

    //免费砸
    egg: function () {
        var ba = new xinyou.ByteArray();
        cc.log("免费砸");
        this.sendGameSocketMsg(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_EGG, ba);
    },

    //金币砸
    goldEgg: function (count) {
        var ba = new xinyou.ByteArray();

        ba.writeByte(count);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_GAME, NetConstant.SUB_GS_GOLDEGG, ba);
    },

    ///**
    // * 登陆到游戏服务器
    // * @param userID 登陆返回的userID
    // * @param userPWD 登陆返回的密码
    // */
    //requestUserLogin: function (userID, userPWD) {
    //    var ba = new xinyou.ByteArray();
    //
    //    ba.writeInt(userID);
    //    ba.writeString('');
    //    ba.writeString(userPWD);
    //    ba.writeInt(3);
    //
    //    xinyou.log("xygame", "login uid:" + userID + " pwd:" + userPWD);
    //    this.sendLoginMessage(NetConstant.SUB_GS_LOGON_USERID, ba);
    //},

    /**
     * 快速坐下
     */
    quickJoinTable: function () {
        this.joinTable(XYConstant.INVALID_TABLE_ID, XYConstant.INVALID_CHAIR_ID, xinyou.gameFrame.wNetDelay);
    },

    /**
     * 加入桌子
     * @param tableID 桌子ID
     * @param chairID 椅子ID
     * @param netDelay 网络延迟
     * @param {string} [password] 桌子密码
     */
    joinTable: function (tableID, chairID, netDelay, password) {
        password = password || '';
        var packet = new xinyou.Packet();
        packet.writeShort(tableID);
        packet.writeShort(chairID);
        packet.writeShort(netDelay);
        if (password != '') {
            packet.writeString(password);
        }
        this.sendGameSocketMsg(NetConstant.MAIN_GS_USER, NetConstant.SUB_GS_USER_SIT_REQ, packet);
    },

    /**
     * 进入房间
     * @param type 房间类型
     */
    inRoom: function (type, subType, isAutoSitDown) {
        currentNetManager.addMyListeners();

        cc.log("inroom");
        var packet = new xinyou.Packet();
        packet.writeByte(type);
        packet.writeByte(subType);
        packet.writeByte(isAutoSitDown);

        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGON, NetConstant.SUB_GS_LOGON_INROOM, packet);
    },

    /**
     * 坐下
     */
    sitDown: function () {
        var packet = new xinyou.Packet();
        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGON, NetConstant.SUB_GS_SIT, packet);
    },

    /**
     * 站起
     */
    standUp: function () {
        var packet = new xinyou.Packet();
        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGON, NetConstant.STANDUP, packet);
    },

    /**
     * 坐到指定座位上
     */
    sitDownChair: function (index, takeGold) {
        var packet = new xinyou.Packet();
        packet.writeByte(index);
        packet.writeInt(takeGold);
        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGON, NetConstant.SUB_GS_SIT_CHAIR, packet);
    },

    /**
     * 创建包厢
     * @param type 房间类型
     */
    createTable: function (baseScore, type, subType, name, password, bixia) {
        var dzbx = bixia ? bixia : 0;//必下
        var packet = new xinyou.Packet();
        packet.writeInt(baseScore);
        packet.writeInt(dzbx);
        packet.writeByte(type);
        packet.writeByte(subType);
        packet.writeMyString(name);
        packet.writeMyString(password);
        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGON, NetConstant.CREATETABLE, packet);
    },

    /**
     * 包厢列表
     * @param type 房间类型
     */
    showTableList: function (type, subType, pageSize, pageIndex, hiddenFull, baseScore) {
        var packet = new xinyou.Packet();
        packet.writeInt(baseScore);
        packet.writeBoolean(hiddenFull);
        packet.writeByte(pageIndex);
        packet.writeInt(pageSize);
        packet.writeByte(type);
        packet.writeByte(subType);
        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGON, NetConstant.TABLELIST, packet);
    },

    /**
     * 坐下指定桌子
     */
    inTable: function (tableId, type, subType, password) {
        var packet = new xinyou.Packet();
        packet.writeByte(type);
        packet.writeByte(subType);
        packet.writeInt(tableId);
        packet.writeMyString(password);
        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGON, NetConstant.INTABLE, packet);
    },

    /**
     * 离开桌子
     */
    leaveTable: function () {
        var packet = new xinyou.Packet();
        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGON, NetConstant.SUB_GS_LEAVETABLE, packet);
    },

    /**
     * 离开房间
     */
    leaveRoom: function () {
        var packet = new xinyou.Packet();
        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGON, NetConstant.SUB_GS_LEAVEROOM, packet);
    },

    /**
     * 准备
     */
    sendReady: function () {
        this.sendFrameMessage(NetConstant.SUB_GS_USER_READY);
    },

    /**
     * 离开座位(当退出房间时,玩家坐在椅子上但没有开始游戏发送)
     */
    standupFromTable: function () {
        this.sendGameSocketMsg(NetConstant.MAIN_GS_USER, NetConstant.SUB_GS_USER_STANDUP_REQ);
    },

    /**
     * 强退游戏(当退出房间时,如果玩家在游戏中发送)
     */
    quitFromTable: function () {
        this.sendGameSocketMsg(NetConstant.MAIN_GS_USER, NetConstant.SUB_GS_USER_LEFT_GAME_REQ);
    },

    sendLoginMessage: function (subCMD, msg) {
        this.sendGameSocketMsg(NetConstant.MAIN_GS_LOGON, subCMD, msg);
    },

    sendGSInfoREQ: function () {
        var packet = new xinyou.Packet();
        packet.writeByte(0);
        this.sendGameSocketMsg(NetConstant.MAIN_GS_FRAME, NetConstant.SUB_GS_INFO, packet);
    },

    /**
     * 发送准备消息
     */
    sendReady: function () {
        this.sendFrameMessage(NetConstant.SUB_GS_USER_READY);
    },

    /**
     * 发送 自动匹配房间 开始匹配
     */
    sendJoinRandomList: function () {
        this.sendUserMessage(NetConstant.SUB_GS_USER_JOIN_RANDOM_LIST_SYN);
    },

    /**
     * 发送框架消息
     * @param subCMD 子消息号
     * @param {xinyou.ByteArray} [msg] 消息体
     */
    sendFrameMessage: function (subCMD, msg) {
        this.sendGameSocketMsg(NetConstant.MAIN_GS_FRAME, subCMD, msg);
    },

    /**
     * 发送游戏消息
     * @param subCMD 子消息号
     * @param {xinyou.ByteArray} [msg] 消息体
     */
    sendGameMessage: function (subCMD, msg) {
        this.sendGameSocketMsg(NetConstant.MAIN_GS_GAME, subCMD, msg);
    },

    /**
     * 发送用户消息
     * @param subCMD 子消息号
     * @param {xinyou.ByteArray} [msg] 消息体
     */
    sendUserMessage: function (subCMD, msg) {
        this.sendGameSocketMsg(NetConstant.MAIN_GS_USER, subCMD, msg);
    },

    /**
     * 发送自定义消息
     * @param mainCMD {number} 大消息号
     * @param subCMD {number} 小消息号
     * @param [msg] {xinyou.ByteArray} 结构体
     */
    sendCustomMessage: function (mainCMD, subCMD, msg) {
        this.sendGameSocketMsg(mainCMD, subCMD, msg);
    },

    /**
     * 组头 发向服务器
     * @param mainCode 主消息号
     * @param subCode 子消息号
     * @param {xinyou.ByteArray} [msg] 消息体
     */
    sendGameSocketMsg: function (mainCode, subCode, msg) {
        var msgCode = makeDWord(mainCode, subCode);

        cc.log("mainCode:" + mainCode + ",subCode:" + subCode + ",msgCode:" + msgCode);
        var packet = new xinyou.ByteArray();
        packet.writeShort(msg ? msg.length + NetConstant.HEAD_SIZE : NetConstant.HEAD_SIZE);
        packet.writeByte(0);
        packet.writeByte(NetConstant.VERSION);
        packet.writeUnsignedInt(msgCode);

        if (msg) {
            packet.writeBytes(msg);
        }
        xinyou.log('发送消息: %d 0x%s 0x%s', Date.now(), mainCode.toString(16), subCode.toString(16));

        this.gameSocket.send(packet.buffer);
    },

    closeGameSocket: function () {
        if (!this.gameSocket || !tyNamespace.isObjectValid(this.gameSocket)) return;
        this.gameSocket.onclose = undefined;
        this.gameSocket.close();
    },

    _gameSocketStateGetter: function () {
        if (!xinyou.objectExist(this.gameSocket))
            return 3;
        return this.gameSocket.readyState;
    },

    get: function (url, cb) {
        if (cc.sys.isNative) {
            var xhr = cc.loader.getXMLHttpRequest();
            xhr.open("GET", url, true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status >= 200 && xhr.status <= 207) {
                        var httpStatus = xhr.statusText;
                        var response = xhr.responseText;
                        cb(null, response);
                    } else {
                        cb(xhr.status);
                    }
                }

            };
            xhr.send();
        }
        else {
            cc.loader.loadTxt(url, cb);
        }
    },

    getJson: function (url, cb) {
        this.get(url, function (err, txt) {
            try {
                if (err || !txt) {
                    return cb(err);
                }
                else {
                    cb(null, JSON.parse(txt));
                }
            } catch (e) {
                cb("load json [" + url + "] failed : " + e);
            }
        });
    },

    /**
     * @param {string} url
     * @param {string|object} content 支持纯字符串或者querystring的object
     * @param {function} cb
     */
    post: function (url, content, cb) {
        var isForms = false;
        if (cc.isObject(content)) {
            content = this._qsStringify(content);
            isForms = true;
        }

        var xhr = cc.loader.getXMLHttpRequest();
        xhr.open("POST", url);
        xhr.setRequestHeader("Content-Type", isForms ? "application/x-www-form-urlencoded" : "text/plain;charset=UTF-8");

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {
                cb(null, {httpStatus: xhr.statusText, response: xhr.responseText});
            }
        };
        xhr.send(content);
    },

    _qsStringify: function (obj) {
        return obj ? Object.keys(obj).map(function (key) {
            var val = obj[key];

            if (Array.isArray(val)) {
                return val.map(function (val2) {
                    return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
                }).join('&');
            }

            return encodeURIComponent(key) + '=' + encodeURIComponent(val);
        }).join('&') : '';
    },

    _qsParse: function (str) {
        if (typeof str !== 'string') {
            return {};
        }

        str = str.trim().replace(/^(\?|#)/, '');

        if (!str) {
            return {};
        }

        return str.trim().split('&').reduce(function (ret, param) {
            var parts = param.replace(/\+/g, ' ').split('=');
            var key = parts[0];
            var val = parts[1];

            key = decodeURIComponent(key);
            // missing `=` should be `null`:
            // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
            val = val === undefined ? null : decodeURIComponent(val);

            if (!ret.hasOwnProperty(key)) {
                ret[key] = val;
            } else if (Array.isArray(ret[key])) {
                ret[key].push(val);
            } else {
                ret[key] = [ret[key], val];
            }

            return ret;
        }, {});
    },

    destroy: function () {
        this.closeGameSocket();
        this.gameSocket = null;
        this.data.destroy();
        this.data = null;
        this.socketData.destroy();
        this.socketData = null;
        this.socketMsgHandler = null;
    }
});

xinyou.netManager = new NetManager();
